package com.yj.ccs.abs.boot.authorization.resolver;

import com.yj.ccs.abs.boot.authorization.annotation.CurrentUser;
import com.yj.ccs.abs.boot.authorization.session.UserSession;
import com.yj.ccs.abs.common.exception.UserUnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Copyright 2018 (C) Yunjian-VC
 * Created on : 2018/3/14
 * Author     : Unbelievable9
 **/
@Service
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    UserSession userSession;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        if (!userSession.isLoggedIn() && methodParameter.hasParameterAnnotation(CurrentUser.class)) {
            throw new UserUnauthorizedException();
        }

        return userSession.getUser();
    }
}
